﻿using Models.API.Param;
using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Web.Common;
using Web.Filters;

namespace Web.Controllers.API
{
    public class PtypeController : ApiController
    {
        [HttpPost]
        public IHttpActionResult InsertPtype([FromBody]Models.API.Param.Ptype entity)
        {
            Result<string> result = new Result<string>();
            try
            {

                string connectionString = "";
                string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
                if (!"OK".Equals(msg))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = msg;
                    result.Data = "Error";
                    result.TotalRows = 0;
                    return Json(result);
                }
                FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);

                if (string.IsNullOrWhiteSpace(entity.UserCode))
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "UserCode不可为空";
                    result.Data = "Warning";
                    return Json(result);
                }
                if (string.IsNullOrWhiteSpace(entity.ParCode))
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "ParCode不可为空";
                    result.Data = "Warning";
                    return Json(result);
                }
                if (Convert.ToInt32(db.GetSingle("select count(*) from Ptype where deleted=0 and UserCode= '" + entity.UserCode + "'")) > 0)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "商品编号[" + entity.UserCode + "]已存在";
                    return Json(result);
                }
                if (!db.Exists("select count(*) from Ptype where deleted=0 and UserCode= '" + entity.ParCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "ParCode[" + entity.ParCode + "]不存在";
                    return Json(result);
                }
                string ParID = db.GetSingle("select typeid from Ptype where deleted=0  and UserCode= '" + entity.ParCode + "'").ToString();

                if (!db.Exists("select count(*) from PTypeCategory where UserCode= '" + entity.CategoryCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "ParCode[" + entity.ParCode + "]不存在";
                    return Json(result);
                }
                string CategoryID = db.GetSingle("select typeid from PTypeCategory where UserCode= '" + entity.CategoryCode + "'").ToString();
                if (string.IsNullOrWhiteSpace(entity.FullName))
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "FullName不可为空";
                    result.Data = "Warning";
                    return Json(result);
                }

                ErpHelper.V993.PtypeParam m = new ErpHelper.V993.PtypeParam();
                m.UserCode = entity.UserCode;
                m.ParId = ParID;
                m.FullName = entity.FullName;
                m.Type = entity.Type;
                m.autotypepycode = FreeADO.Common.StringPlus.GetFirstPYLetter(m.Type);
                m.Standard = entity.Standard;
                m.Comment = entity.Comment;
                m.PtypeCategoryID = CategoryID;
                m.IfSerial = entity.IfSerial.ToString();
                m.Pycode = FreeADO.Common.StringPlus.GetFirstPYLetter(m.FullName);

                var re=ErpHelper.V993.ErpHelper.InsertPtype(db, m);
                result.Type = (AjaxResultType)re.Type;
                result.Content = re.Content;
                result.TotalRows = 0;
                result.Data = "";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = "";
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        [HttpPost]
        public IHttpActionResult UpdatePtype([FromBody]Models.API.Param.Ptype entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            if (string.IsNullOrWhiteSpace(entity.UserCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }
            if (string.IsNullOrWhiteSpace(entity.ParCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "ParCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }
            if (Convert.ToInt32(db.GetSingle("select count(*) from Ptype where deleted=0 and UserCode= '" + entity.UserCode + "'")) == 0)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "商品编号[" + entity.UserCode + "]不存在";
                return Json(result);
            }
            string TypeID= db.GetSingle("select typeid from Ptype where deleted=0  and UserCode= '" + entity.UserCode + "'").ToString();

            if (!db.Exists("select count(*) from Ptype where deleted=0 and UserCode= '" + entity.ParCode + "'"))
            {
                result.Type = AjaxResultType.Error;
                result.Content = "ParCode[" + entity.ParCode + "]不存在";
                return Json(result);
            }
            string ParID = db.GetSingle("select typeid from Ptype where deleted=0  and UserCode= '" + entity.ParCode + "'").ToString();

            if (!db.Exists("select count(*) from PTypeCategory where UserCode= '" + entity.CategoryCode + "'"))
            {
                result.Type = AjaxResultType.Error;
                result.Content = "ParCode[" + entity.ParCode + "]不存在";
                return Json(result);
            }
            string CategoryID = db.GetSingle("select typeid from PTypeCategory where UserCode= '" + entity.CategoryCode + "'").ToString();
            if (string.IsNullOrWhiteSpace(entity.FullName))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "FullName不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            try
            {
                DataTable dt = db.Query("select * from ptype where typeid='" + TypeID + "'").Tables[0];
                DataTable edt = db.Query("select * from QP_PType_Ext where PtypeID='" + TypeID + "'").Tables[0];
                DataTable pdt = db.Query("select * from PType_Price where PtypeID='" + TypeID + "' and isdefaultunit=1").Tables[0];
                string Brand = "";
                string Import = "";
                string GeneralType = "";
                string GeneralDwgNo = "";
                string Property = "";
                string PackageQty = "";
                string Weight = "";
                string TaxNumber = "";
                decimal Taxrate = 0;
                string BTypeID = "";
                string FcUnit = "";
                decimal FcPrice = 0;
                if (edt.Rows.Count>0)
                {
                    Brand = edt.Rows[0]["Brand"].ToString();
                    Import = edt.Rows[0]["Import"].ToString();
                    GeneralType = edt.Rows[0]["GeneralType"].ToString();
                    GeneralDwgNo = edt.Rows[0]["GeneralDwgNo"].ToString();
                    Property = edt.Rows[0]["Property"].ToString();
                    PackageQty = edt.Rows[0]["PackageQty"].ToString();
                    Weight = edt.Rows[0]["Weight"].ToString();
                    TaxNumber = edt.Rows[0]["TaxNumber"].ToString();
                    Taxrate = Convert.ToDecimal(edt.Rows[0]["Taxrate"]);
                    BTypeID = edt.Rows[0]["BTypeID"].ToString();
                    FcUnit = edt.Rows[0]["FcUnit"].ToString();
                    FcPrice = Convert.ToDecimal(edt.Rows[0]["FcPrice"]);
                }
               decimal  PreBuyPrice1      =0;
               decimal  PreBuyPrice2      =0;
               decimal  PreBuyPrice3      =0;
               decimal  PreBuyPrice4      =0;
               decimal  PreBuyPrice5      =0;
               decimal  TopBuyPrice       =0;
               decimal  PreSalePrice1     =0;
               decimal  PreSalePrice2     =0;
               decimal  PreSalePrice3     =0;
               decimal  PreSalePrice4     =0;
               decimal  PreSalePrice5     =0;
               decimal  PreSalePrice6     =0;
               decimal  PreSalePrice7     =0;
               decimal  PreSalePrice8     =0;
               decimal  PreSalePrice9     =0;
               decimal  PreSalePrice10    =0;
               decimal  RetailPrice       =0;
                decimal TopSalePrice = 0;
                decimal LowSalePrice = 0;

                if (pdt.Rows.Count > 0)
                {
                    PreBuyPrice1 = !DBNull.Value.Equals(pdt.Rows[0]["PreBuyPrice1"]) ? Convert.ToDecimal(pdt.Rows[0]["PreBuyPrice1"]) : 0;
                    PreBuyPrice2 = !DBNull.Value.Equals(pdt.Rows[0]["PreBuyPrice2"]) ? Convert.ToDecimal(pdt.Rows[0]["PreBuyPrice2"]) : 0;
                    PreBuyPrice3 = !DBNull.Value.Equals(pdt.Rows[0]["PreBuyPrice3"]) ? Convert.ToDecimal(pdt.Rows[0]["PreBuyPrice3"]) : 0;
                    PreBuyPrice4 = !DBNull.Value.Equals(pdt.Rows[0]["PreBuyPrice4"]) ? Convert.ToDecimal(pdt.Rows[0]["PreBuyPrice4"]) : 0;
                    PreBuyPrice5 = !DBNull.Value.Equals(pdt.Rows[0]["PreBuyPrice5"]) ? Convert.ToDecimal(pdt.Rows[0]["PreBuyPrice5"]) : 0;
                    TopBuyPrice = !DBNull.Value.Equals(pdt.Rows[0]["TopBuyPrice"]) ? Convert.ToDecimal(pdt.Rows[0]["TopBuyPrice"]) : 0;
                    PreSalePrice1 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice1"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice1"]) : 0;
                    PreSalePrice2 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice2"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice2"]) : 0;
                    PreSalePrice3 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice3"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice3"]) : 0;
                    PreSalePrice4 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice4"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice4"]) : 0;
                    PreSalePrice5 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice5"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice5"]) : 0;
                    PreSalePrice6 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice6"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice6"]) : 0;
                    PreSalePrice7 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice7"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice7"]) : 0;
                    PreSalePrice8 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice8"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice8"]) : 0;
                    PreSalePrice9 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice9"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice9"]) : 0;
                    PreSalePrice10 = !DBNull.Value.Equals(pdt.Rows[0]["PreSalePrice10"]) ? Convert.ToDecimal(pdt.Rows[0]["PreSalePrice10"]) : 0;
                    RetailPrice = !DBNull.Value.Equals(pdt.Rows[0]["RetailPrice"]) ? Convert.ToDecimal(pdt.Rows[0]["RetailPrice"]) : 0;
                    TopSalePrice = !DBNull.Value.Equals(pdt.Rows[0]["TopSalePrice"]) ? Convert.ToDecimal(pdt.Rows[0]["TopSalePrice"]) : 0;
                    LowSalePrice = !DBNull.Value.Equals(pdt.Rows[0]["LowSalePrice"]) ? Convert.ToDecimal(pdt.Rows[0]["LowSalePrice"]) : 0;
                }





                    ErpHelper.V993.PtypeParam m = new ErpHelper.V993.PtypeParam();
                m.TypeID = TypeID;
                m.UserCode = entity.UserCode;
                m.ParId = ParID;
                m.FullName = entity.FullName;
                m.Type = entity.Type;
                m.autotypepycode = FreeADO.Common.StringPlus.GetFirstPYLetter(m.Type);
                m.Standard = entity.Standard;
                m.Comment = entity.Comment;
                m.PtypeCategoryID = CategoryID;
                m.IfSerial = entity.IfSerial.ToString();
                m.Pycode = FreeADO.Common.StringPlus.GetFirstPYLetter(m.FullName);

                foreach (DataRow item in dt.Rows)
                {
                    m.Area = !DBNull.Value.Equals(item["Area"]) ? item["Area"].ToString() :m.Area;
                    m.AssistantUnitId = !DBNull.Value.Equals(item["AssistantUnitId"]) ? item["AssistantUnitId"].ToString() : m.AssistantUnitId;
                    m.baseUnitid = !DBNull.Value.Equals(item["baseUnitid"]) ? item["baseUnitid"].ToString() : m.baseUnitid;
                    m.Brand = Brand;
                    m.BTypeID = BTypeID;
                    m.BuyDefaultRate = !DBNull.Value.Equals(item["BuyDefaultRate"]) ? Convert.ToDecimal(item["BuyDefaultRate"]) : m.BuyDefaultRate;
                    m.BuyUnitId = !DBNull.Value.Equals(item["BuyUnitId"]) ? item["BuyUnitId"].ToString() : m.BuyUnitId;
                    m.ColorGroupID = !DBNull.Value.Equals(item["ColorGroupID"]) ? item["ColorGroupID"].ToString() : m.ColorGroupID;
                    m.customitemfrom = DBNull.Value.Equals(item["customitemfrom"]) ? item["customitemfrom"].ToString() : m.customitemfrom;
                    m.customitemid = !DBNull.Value.Equals(item["customitemid"]) ? item["customitemid"].ToString() : m.customitemid;
                    m.customitemname = !DBNull.Value.Equals(item["customitemname"]) ? item["customitemname"].ToString() : m.customitemname;
                    m.customitemrefid = !DBNull.Value.Equals(item["customitemrefid"]) ? item["customitemrefid"].ToString() : m.customitemrefid;
                    m.DwgNo = !DBNull.Value.Equals(item["DwgNo"]) ? item["DwgNo"].ToString() : m.DwgNo;
                    m.EntryCode = !DBNull.Value.Equals(item["EntryCode"]) ? item["EntryCode"].ToString() : m.EntryCode;
                    m.FcPrice = FcPrice.ToString();
                    m.FcUnit = FcUnit;
                    m.GeneralDwgNo = GeneralDwgNo;
                    m.GeneralType = GeneralType;
                    m.IfUseEntryCode = !DBNull.Value.Equals(item["IfUseEntryCode"]) ? Convert.ToInt32(item["IfUseEntryCode"]) : m.IfUseEntryCode;
                    m.IfUseGoodsNum = !DBNull.Value.Equals(item["IfUseGoodsNum"]) ? Convert.ToInt32(item["IfUseGoodsNum"]) : m.IfUseGoodsNum;
                    m.Import = Import;
                    m.integral = !DBNull.Value.Equals(item["integral"]) ? item["integral"].ToString() : m.integral;
                    m.InventoryTypeID = !DBNull.Value.Equals(item["InventoryTypeID"]) ? item["InventoryTypeID"].ToString() : m.InventoryTypeID;
                    m.iscombinationproduct = !DBNull.Value.Equals(item["iscombinationproduct"]) ? Convert.ToInt32(item["iscombinationproduct"]) : m.iscombinationproduct;
                    m.isitgift = !DBNull.Value.Equals(item["isitgift"]) ? Convert.ToInt32(item["isitgift"]) : m.isitgift;
                    m.IsScaleWeight = !DBNull.Value.Equals(item["IsScaleWeight"]) ? Convert.ToInt32(item["IsScaleWeight"]) : m.IsScaleWeight;
                    m.isservice = !DBNull.Value.Equals(item["isservice"]) ? Convert.ToInt32(item["isservice"]) : m.isservice;
                    m.LowSalePrice = LowSalePrice;
                    m.Name = !DBNull.Value.Equals(item["Name"]) ? item["Name"].ToString() : m.Name;
                    m.omprice = !DBNull.Value.Equals(item["omprice"]) ? Convert.ToDecimal(item["omprice"]) : m.omprice;
                    m.Omuse = !DBNull.Value.Equals(item["Omuse"]) ? Convert.ToInt32(item["Omuse"]) : m.Omuse;
                    m.othercomment1 = !DBNull.Value.Equals(item["othercomment1"]) ? item["othercomment1"].ToString() : m.othercomment1;
                    m.othercomment2 = !DBNull.Value.Equals(item["othercomment2"]) ? item["othercomment2"].ToString() : m.othercomment2;
                    m.othercomment3 = !DBNull.Value.Equals(item["othercomment3"]) ? item["othercomment3"].ToString() : m.othercomment3;
                    m.othercomment4 = !DBNull.Value.Equals(item["othercomment4"]) ? item["othercomment4"].ToString() : m.othercomment4;
                    m.othercomment5 = !DBNull.Value.Equals(item["othercomment5"]) ? item["othercomment5"].ToString() : m.othercomment5;
                    m.PackageQty = PackageQty;
                    m.pluCode = !DBNull.Value.Equals(item["pluCode"]) ? Convert.ToInt32(item["pluCode"]) : m.pluCode;
                    m.PreBuyPrice1 = PreBuyPrice1;
                    m.PreBuyPrice2 = PreBuyPrice2;
                    m.PreBuyPrice3 = PreBuyPrice3;
                    m.PreBuyPrice4 = PreBuyPrice4;
                    m.PreBuyPrice5 = PreBuyPrice5;
                    m.PreSalePrice1 = PreSalePrice1;
                    m.PreSalePrice10 = PreSalePrice10;
                    m.PreSalePrice2 = PreSalePrice2;
                    m.PreSalePrice3 = PreSalePrice3;
                    m.PreSalePrice4 = PreSalePrice4;
                    m.PreSalePrice5 = PreSalePrice5;
                    m.PreSalePrice6 = PreSalePrice6;
                    m.PreSalePrice7 = PreSalePrice7;
                    m.PreSalePrice8 = PreSalePrice8;
                    m.PreSalePrice9 = PreSalePrice9;
                    m.ProduceUnitId = !DBNull.Value.Equals(item["ProduceUnitId"]) ? item["ProduceUnitId"].ToString() : m.ProduceUnitId;
                    m.Property = Property;
                    m.PtypeBrandarID = !DBNull.Value.Equals(item["BrandarTypeID"]) ? item["BrandarTypeID"].ToString() : m.PtypeBrandarID;
                    m.Pweight = !DBNull.Value.Equals(item["weight"]) ? Convert.ToDecimal(item["weight"]) : m.Pweight;
                    m.RetailPrice = RetailPrice;
                    m.SaleDefaultRate = !DBNull.Value.Equals(item["SaleDefaultRate"]) ? Convert.ToDecimal(item["SaleDefaultRate"]) : m.SaleDefaultRate;
                    m.SaleUnitId = !DBNull.Value.Equals(item["SaleUnitId"]) ? item["SaleUnitId"].ToString() : m.SaleUnitId;
                    m.ScaleWeightType = !DBNull.Value.Equals(item["ScaleWeightType"]) ? Convert.ToInt32(item["ScaleWeightType"]) : m.ScaleWeightType;
                    m.SerialCount = !DBNull.Value.Equals(item["SerialCount"]) ? item["SerialCount"].ToString() : m.SerialCount;
                    m.SizeGroupID = !DBNull.Value.Equals(item["SizeGroupID"]) ? item["SizeGroupID"].ToString() : m.SizeGroupID;
                    m.SonNum = !DBNull.Value.Equals(item["SonNum"]) ? Convert.ToInt32(item["SonNum"]) : m.SonNum;
                    m.sortid = !DBNull.Value.Equals(item["sortid"]) ? Convert.ToInt32(item["sortid"]) : m.sortid;
                    m.StockUnitId = !DBNull.Value.Equals(item["StockUnitId"]) ? item["StockUnitId"].ToString() : m.StockUnitId;
                    m.TaxNumber = TaxNumber;
                    m.Taxrate = Taxrate.ToString();
                    m.TopBuyPrice = TopBuyPrice;
                    m.TopSalePrice = TopSalePrice;
                    m.TypeID = !DBNull.Value.Equals(item["TypeID"]) ? item["TypeID"].ToString() : m.TypeID;
                    m.Unit1 = !DBNull.Value.Equals(item["Unit1"]) ? item["Unit1"].ToString() : m.Unit1;
                    m.Unit2 = !DBNull.Value.Equals(item["Unit2"]) ? item["Unit2"].ToString() : m.Unit2;
                    m.UnitRate1 = !DBNull.Value.Equals(item["UnitRate1"]) ? item["UnitRate1"].ToString() : m.UnitRate1;
                    m.UnitRate2 = !DBNull.Value.Equals(item["UnitRate2"]) ? item["UnitRate2"].ToString() : m.UnitRate2;
                    m.UnitsType = !DBNull.Value.Equals(item["UnitsType"]) ? Convert.ToInt32(item["UnitsType"]) : m.UnitsType;
                    m.UsefulLifeDay = !DBNull.Value.Equals(item["UsefulLifeDay"]) ? item["UsefulLifeDay"].ToString() : m.UsefulLifeDay;
                    m.UsefulLifeMonth = !DBNull.Value.Equals(item["UsefulLifeMonth"]) ? item["UsefulLifeMonth"].ToString() : m.UsefulLifeMonth;
                    m.ValidDays = !DBNull.Value.Equals(item["ValidDays"]) ? item["ValidDays"].ToString() : m.ValidDays;
                    m.volume = !DBNull.Value.Equals(item["volume"]) ? Convert.ToDecimal(item["volume"]) : m.volume;
                    m.Weight = Weight;
                }

                var re= ErpHelper.V993.ErpHelper.UpdatePtype(db, m);


                result.Type = (AjaxResultType)re.Type;
                result.Content = re.Content;
                result.TotalRows = 0;
                result.Data = "";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = "";
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeletePtype([FromBody]Models.API.Param.Ptype entity)
        {
            Result<string> result = new Result<string>();
            try
            {

                string connectionString = "";
                string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
                if (!"OK".Equals(msg))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = msg;
                    result.Data = "Error";
                    result.TotalRows = 0;
                    return Json(result);
                }

                if (string.IsNullOrWhiteSpace(entity.UserCode))
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "UserCode不可为空";
                    result.Data = "Warning";
                    return Json(result);
                }

                SqlParameter[] parameters = {
                    new SqlParameter("@typeid",SqlDbType.VarChar,100),
                    new SqlParameter("@dbname",SqlDbType.VarChar,100),
                    new SqlParameter("@deltype",SqlDbType.Int)
                };

                string strSQL = "select typeid from Ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.UserCode);
                string typeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();

                parameters[0].Value = typeid;
                parameters[1].Value = "Ptype";
                parameters[2].Value = 0;

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_StopBaseInfo", parameters, out resultCount);

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 查询商品
        /// </summary>
        /// <param name="TypeId">商品ID</param>
        /// <param name="UserCode">编号</param>
        /// <param name="FullName">名称</param>
        /// <param name="Name">简称</param>
        /// <param name="Standard">规格</param>
        /// <param name="Type">型号</param>
        /// <param name="Delfg">删除标识</param>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">每页大小</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SelectPtype(dynamic dyobj)
        {
            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            string strSQL;
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }

            try
            {
                strSQL = "";
                strSQL += " select ";
                strSQL += " ISNULL((select FullName from PtypeCategory where typeid=ptype.PtypeCategoryID),'') as cateFullName ";

                strSQL += " ,Ptype.ParId ";
                strSQL += " ,Ptype.UserCode ";
                strSQL += " ,Ptype.FullName ";
                strSQL += " ,Ptype.Name ";
                strSQL += " ,Ptype.PyCode ";
                strSQL += " ,Ptype.IsItGift ";
                //strSQL += " ,gp_CruPtypeSerial.Serial "; 
                strSQL += " ,Standard ";
                strSQL += " ,Type ";
                strSQL += " ,Unit1 ";
                strSQL += " ,Unit2 ";
                strSQL += " ,Preprice1 ";
                strSQL += " ,Preprice2 ";
                strSQL += " ,Preprice3 ";
                strSQL += " ,Preprice4 ";
                strSQL += " ,Preprice5 ";
                strSQL += " ,Ptype.Comment ";
                strSQL += " ,EntryCode ";
                strSQL += " ,MultEntryCode ";
                strSQL += " ,IfSerial ";
                strSQL += " ,isnull(Costom1,'') as Costom1 ";
                strSQL += " ,isnull(Costom2,'') as Costom2 ";
                strSQL += " ,isnull(Costom3,'') as Costom3 ";
                strSQL += " ,isnull(Costom4,'') as Costom4 ";
                strSQL += " ,isnull(Costom5,'') as Costom5 ";
                strSQL += " from Ptype ";
                strSQL += " left join Ptype_CustomColumns on Ptype.typeId = Ptype_CustomColumns.typeid ";
                //strSQL += " left join gp_CruPtypeSerial on Ptype.typeId = gp_CruPtypeSerial.PtypeID ";
                strSQL += " where 1=1 ";

                //if (null != mydyobj.TypeId && !string.IsNullOrWhiteSpace(mydyobj.TypeId.ToString()))
                //    strSQL += " and Ptype.typeId = N'" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.TypeId.ToString());

                string strsqlcount = "";
                strsqlcount += "select count(*) ";
                strsqlcount += " from Ptype ";
                strsqlcount += " left join Ptype_CustomColumns on Ptype.typeId = Ptype_CustomColumns.typeid ";
                //strSQL += " left join gp_CruPtypeSerial on Ptype.typeId = gp_CruPtypeSerial.PtypeID ";
                strsqlcount += " where 1=1 ";




                if (null != mydyobj.UserCode && !string.IsNullOrWhiteSpace(mydyobj.UserCode.ToString()))
                {
                    strSQL += " and UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.UserCode.ToString());
                    strsqlcount += " and UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.UserCode.ToString());
                }
                if (null != mydyobj.FullName && !string.IsNullOrWhiteSpace(mydyobj.FullName.ToString()))
                {
                    strSQL += " and FullName like '%" + mydyobj.FullName.ToString() + "%'";
                    strsqlcount += " and FullName like '%" + mydyobj.FullName.ToString() + "%'";
                }
                if (null != mydyobj.Name && !string.IsNullOrWhiteSpace(mydyobj.Name.ToString()))
                {
                    strSQL += " and Name like '%" + mydyobj.Name.ToString() + "%'";
                    strsqlcount += " and Name like '%" + mydyobj.Name.ToString() + "%'";
                }
                if (null != mydyobj.Standard && !string.IsNullOrWhiteSpace(mydyobj.Standard.ToString()))
                {
                    strSQL += " and Standard like '%" + mydyobj.Standard.ToString() + "%'";//规格
                    strsqlcount += " and Standard like '%" + mydyobj.Standard.ToString() + "%'";//规格
                }
                if (null != mydyobj.Type && !string.IsNullOrWhiteSpace(mydyobj.Type.ToString()))
                {
                    strSQL += " and Type like '%" + mydyobj.Type.ToString() + "%'";//型号
                    strsqlcount += " and Type like '%" + mydyobj.Type.ToString() + "%'";//型号
                }
                if (null != mydyobj.Code && !string.IsNullOrWhiteSpace(mydyobj.Code.ToString()))
                {
                    strSQL += " and (EntryCode like '%" + mydyobj.Code.ToString() + "%'";//条码
                    strSQL += " or MultEntryCode like '%" + mydyobj.Code.ToString() + "%')";
                    strsqlcount += " and (EntryCode like '%" + mydyobj.Code.ToString() + "%'";//条码
                    strsqlcount += " or MultEntryCode like '%" + mydyobj.Code.ToString() + "%')";
                }

                if (null != mydyobj.PyCode && !string.IsNullOrWhiteSpace(mydyobj.PyCode.ToString()))
                {
                    strSQL += " and Ptype.PyCode like '%" + mydyobj.PyCode.ToString() + "%'";//拼音码
                    strsqlcount += " and Ptype.PyCode like '%" + mydyobj.PyCode.ToString() + "%'";//拼音码
                }
                //if (null != mydyobj.Serial && !string.IsNullOrWhiteSpace(mydyobj.Serial.ToString()))
                //    strSQL += " and gp_CruPtypeSerial.Serial like '%" + mydyobj.Serial.ToString() + "%'";//序列号

                if (null != mydyobj.Delfg && "0".Equals(mydyobj.Delfg.ToString()))
                {
                    strSQL += " and deleted = '0'";
                    strsqlcount += " and deleted = '0'";
                }

                strSQL += " order by Ptype.typeId asc ";

                if (!"0".Equals(mydyobj.PageIndex.ToString()) && !"0".Equals(mydyobj.PageSize.ToString()))
                {
                    strSQL += " offset " + (Convert.ToInt32(mydyobj.PageIndex.ToString()) - 1) * Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows fetch next " + Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows only";
                }




                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                result.TotalRows = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(strsqlcount));

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;
                //  result.TotalRows = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        #region  2023-03-23 新增 验证赠品是否可以赠送
        /// <summary>
        /// 验证赠品是否可以赠送
        /// </summary>
        /// <param name="KtypeId">仓库ID</param>
        /// <param name="UserCode">编号</param>
        /// <param name="FullName">名称</param>
        /// <param name="StoreId">账套ID</param>
        /// <param name="IsGift">赠品</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult VerifyIsGift(dynamic dyobj)
        {
            Result<string> result = new Result<string>();
            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            if (string.IsNullOrWhiteSpace(dyobj.KtypeId.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "KtypeID不可为空";
                result.Data = "Warning";
                return Json(result);
            }
            if (string.IsNullOrWhiteSpace(dyobj.UserCode.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }
            try
            {
                if ("197".Equals(dyobj.StoreId.ToString())&&"1".Equals(dyobj.IsGift.ToString()))
                {
                    string strSQL = "select IsItGift,FullName from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(dyobj.UserCode.ToString());
                    DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                    if (dt.Rows.Count > 0)
                    {
                        if (string.IsNullOrWhiteSpace(dt.Rows[0]["IsItGift"].ToString()) || dt.Rows[0]["IsItGift"].ToString() == "False")
                        {
                            result.Type = AjaxResultType.Warning;
                            result.Content = dt.Rows[0]["FullName"].ToString()+ " 为不可赠送商品!";
                            result.TotalRows = 0;
                            result.Data = "Warning";
                        }
                        else
                        {
                            result.Type = AjaxResultType.Success;
                            result.Content = "可赠送";
                            result.TotalRows = 0;
                            result.Data = "OK";
                        }
                    }
                    else
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "商品查询失败!";
                        result.TotalRows = 0;
                        result.Data = "Warning";
                    }
                }
                else
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "";
                    result.TotalRows = 0;
                    result.Data = "OK";
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        #endregion
        /// <summary>
        /// 查询商品库存
        /// </summary>
        /// <param name="UserCode">商品ID</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetPtype(dynamic dyobj)
        {
            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            string strSQL;
            ResultSerial<DataTable, DataTable> result = new ResultSerial<DataTable, DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                return Json(result);
            }

            //if (null == mydyobj.KtypeId || string.IsNullOrWhiteSpace(mydyobj.KtypeId.ToString()))
            //{
            //    result.Type = AjaxResultType.Warning;
            //    result.Content = "KtypeId不可为空";
            //    return Json(result);
            //}

            try
            {

                //库存列表
                strSQL = "";
                strSQL += "select ";
                strSQL += " Ptype.UserCode as PtypeId ";//商品编号
                strSQL += " ,ISNULL((select FullName from PtypeCategory where typeid=Ptype.PtypeCategoryID),'') as cateFullName ";//商品类别
                strSQL += " ,Ptype.FullName ";//商品名
                strSQL += " ,Ptype.PyCode ";//拼音码IfSerial
                strSQL += " ,Ptype.IfSerial ";//是否强制序列号 1是 0否
                strSQL += " ,Ptype.IsItGift ";//可否为赠品
                strSQL += " ,ISNULL(stock.UserCode,'') as KtypeId ";//仓库ID
                strSQL += " ,ISNULL(stock.FullName,'') as Kname ";//仓库名称
                strSQL += " ,ISNULL(ct.UserCode,'') as CargoCode ";
                strSQL += " ,ISNULL(ct.FullName,'') as CargoName ";
                strSQL += " ,ISNULL(ct.Comment,'') as CargoComment ";
                strSQL += " ,ISNULL(GoodsStocks.ProduceDate, '') as ProduceDate  ";//生产日期   2022-06-15添加       	
                strSQL += " ,ISNULL(Convert(int,GoodsStocks.Qty),0) as Qty ";//数量
                strSQL += " ,ISNULL(GoodsCostPrice,0) as Price ";//单价
                strSQL += " ,ISNULL(PType_Price.PreSalePrice1, 0) as PrePrice  ";//预售价1
                strSQL += " ,ISNULL(PType_Price.LowSalePrice, 0) as LowSalePrice ";//最低销售价
                strSQL += " ,ISNULL(GoodsCostPrice,0)*ISNULL(Qty,0) as Total ";//金额
                strSQL += " ,Ptype.IsService ";//是否服务商品
                strSQL += " from Ptype ";
                strSQL += " left join GOODSSTOCKS_QTY as GoodsStocks on Ptype.typeId = GoodsStocks.PtypeID ";
                strSQL += " left join stock on stock.typeId = GoodsStocks.KtypeID ";
                strSQL += " left join PType_Price on Ptype.typeId =PType_Price.ptypeid ";
                strSQL += " left join CargoType as ct on GoodsStocks.CargoID=ct.CargoID ";
                strSQL += " where 1=1 ";

                string strsqlcount1 = "";
                strsqlcount1 += "select count(*) ";
                strsqlcount1 += " from Ptype ";
                strsqlcount1 += " left join GoodsStocks on Ptype.typeId = GoodsStocks.PtypeID ";
                strsqlcount1 += " left join stock on stock.typeId = GoodsStocks.KtypeID ";
                strsqlcount1 += " left join PType_Price on Ptype.typeId =PType_Price.ptypeid ";
                strsqlcount1 += " where 1=1 ";

                //if ("197".Equals(mydyobj.StoreId.ToString())&&"1".Equals(mydyobj.IsGift.ToString()))
                //{
                //    strSQL += " and Ptype.IsItGift =1";
                //    strsqlcount1 += " and Ptype.IsItGift =1";
                //}

                //仓库ID 
                if (null != mydyobj.KtypeId && !string.IsNullOrWhiteSpace(mydyobj.KtypeId.ToString()))
                {
                    strSQL += " and (stock.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.KtypeId.ToString());
                    strSQL += " or Ptype.IsService = '1') ";//服务类商品


                    strsqlcount1 += " and (stock.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.KtypeId.ToString());
                    strsqlcount1 += " or Ptype.IsService = '1') ";//服务类商品


                }
                //strSQL += " and stock.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.KtypeId.ToString());

                //商品ID
                if (null != mydyobj.UserCode && !string.IsNullOrWhiteSpace(mydyobj.UserCode.ToString()))
                {
                    strSQL += " and Ptype.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.UserCode.ToString());
                    strsqlcount1 += " and Ptype.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.UserCode.ToString());
                }

                if ("5".Equals(mydyobj.StoreId.ToString()))
                {
                    /// 2023-03-22 新增 UserCode 模糊查询
                    //商品名或商品UserCode 
                    if (null != mydyobj.FullName && !string.IsNullOrWhiteSpace(mydyobj.FullName.ToString()))
                    {
                        strSQL += " and (Ptype.FullName like '%" + mydyobj.FullName.ToString() + "%' or Ptype.UserCode like '%" + mydyobj.FullName.ToString() + "%')";
                        strsqlcount1 += " and (Ptype.FullName like '%" + mydyobj.FullName.ToString() + "%' or Ptype.UserCode like '%" + mydyobj.FullName.ToString() + "%')";
                    }
                }
                else
                {
                    //商品名
                    if (null != mydyobj.FullName && !string.IsNullOrWhiteSpace(mydyobj.FullName.ToString()))
                    {
                        strSQL += " and Ptype.FullName like '%" + mydyobj.FullName.ToString() + "%'";
                        strsqlcount1 += " and Ptype.FullName like '%" + mydyobj.FullName.ToString() + "%'";
                    }
                }


                //拼音码
                if (null != mydyobj.PyCode && !string.IsNullOrWhiteSpace(mydyobj.PyCode.ToString()))
                {
                    strSQL += " and Ptype.PyCode like '%" + mydyobj.PyCode.ToString() + "%'";
                    strsqlcount1 += " and Ptype.PyCode like '%" + mydyobj.PyCode.ToString() + "%'";
                }
                //商品类别 2022-06-14添加商品类别查询条件
                if (null != mydyobj.PtypeCategoryCode && !string.IsNullOrWhiteSpace(mydyobj.PtypeCategoryCode.ToString()))
                {
                    strSQL += " and Ptype.PtypeCategoryID =(select typeid from PtypeCategory where UserCode = '" + mydyobj.PtypeCategoryCode.ToString() + "') ";
                    strsqlcount1 += " and Ptype.PtypeCategoryID =(select typeid from PtypeCategory where UserCode = '" + mydyobj.PtypeCategoryCode.ToString() + "') ";
                }
                if (null == mydyobj.PageIndex || string.IsNullOrWhiteSpace(mydyobj.PageIndex.ToString()))
                {
                    mydyobj.PageIndex = 1;
                }
                if (null == mydyobj.PageSize || string.IsNullOrWhiteSpace(mydyobj.PageSize.ToString()))
                {
                    mydyobj.PageSize = 2000000000;
                }
                strSQL += @"order by ptype.typeId 
offset " + (mydyobj.PageSize * (mydyobj.PageIndex - 1)).ToString() + " rows fetch next " + mydyobj.PageSize.ToString() + @" rows only";
                DataTable dt1 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];


                result.TotalRows1 = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(strsqlcount1));




                //序列号列表
                strSQL = "";
                strSQL += "select ";
                strSQL += " gp_CruPtypeSerial.Serial ";//序列号
                strSQL += " ,stock.UserCode as KtypeID ";//仓库编号
                strSQL += " ,Ptype.UserCode as PtypeID";//商品编号
                strSQL += " ,ISNULL((select FullName from PtypeCategory where typeid=Ptype.PtypeCategoryID),'') as cateFullName ";//商品类别
                strSQL += " ,Ptype.FullName ";//商品名
                strSQL += " ,b1.UserCode as BTypeID1 ";//客户ID
                strSQL += " ,b2.UserCode as BTypeID2 ";//供货商ID
                strSQL += " ,gp_CruPtypeSerial.InKtypeTime ";//入库日期
                strSQL += " ,gp_CruPtypeSerial.OutKtypeTime ";//出库日期
                strSQL += " ,ISNULL(gp_CruPtypeSerial.ProduceDate, '') as ProduceDate  ";//生产日期 2022-06-15添加
                strSQL += " ,ISNULL(gp_CruPtypeSerial.CostPrice,0) as CostPrice  ";//成本单价2022-06-13
                strSQL += " ,gp_CruPtypeSerial.Flag ";//在库标识
                strSQL += " ,Ptype.IsService ";//是否服务商品
                strSQL += " ,ct.UserCode as CargoCode ";
                strSQL += " ,ct.FullName as CargoName ";
                strSQL += " ,ct.Comment as CargoComment";
                strSQL += " from Ptype ";
                strSQL += " left join gp_CruPtypeSerial on Ptype.typeId = gp_CruPtypeSerial.PtypeID ";
                strSQL += " left join stock on stock.typeId = gp_CruPtypeSerial.KtypeID ";
                strSQL += " left join btype as b1 on b1.typeId = gp_CruPtypeSerial.BTypeID1 ";
                strSQL += " left join btype as b2 on b2.typeId = gp_CruPtypeSerial.BTypeID2 ";
                strSQL += " left join CargoType as ct on gp_CruPtypeSerial.CargoID=ct.CargoID ";
                strSQL += " where 1=1 ";

                string strsqlcount2 = "";
                strsqlcount2 += "select count(*)";

                strsqlcount2 += " from Ptype ";
                strsqlcount2 += " left join gp_CruPtypeSerial on Ptype.typeId = gp_CruPtypeSerial.PtypeID ";
                strsqlcount2 += " left join stock on stock.typeId = gp_CruPtypeSerial.KtypeID ";
                strsqlcount2 += " left join btype as b1 on b1.typeId = gp_CruPtypeSerial.BTypeID1 ";
                strsqlcount2 += " left join btype as b2 on b2.typeId = gp_CruPtypeSerial.BTypeID2 ";
                strsqlcount2 += " where 1=1 ";

                //仓库ID
                if (null != mydyobj.KtypeId && !string.IsNullOrWhiteSpace(mydyobj.KtypeId.ToString()))
                {
                    strSQL += " and (stock.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.KtypeId.ToString());
                    strSQL += " or Ptype.IsService = '1') ";//服务类商品

                    strsqlcount2 += " and (stock.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.KtypeId.ToString());
                    strsqlcount2 += " or Ptype.IsService = '1') ";//服务类商品
                }
                //strSQL += " and (stock.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.KtypeId.ToString());
                //strSQL += " or Ptype.IsService = '1') ";//服务类商品

                //商品ID
                if (null != mydyobj.UserCode && !string.IsNullOrWhiteSpace(mydyobj.UserCode.ToString()))
                {
                    strSQL += " and Ptype.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.UserCode.ToString());
                    strsqlcount2 += " and Ptype.UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.UserCode.ToString());
                }
                //商品名
                if (null != mydyobj.FullName && !string.IsNullOrWhiteSpace(mydyobj.FullName.ToString()))
                {
                    strSQL += " and Ptype.FullName like '%" + mydyobj.FullName.ToString() + "%'";
                    strsqlcount2 += " and Ptype.FullName like '%" + mydyobj.FullName.ToString() + "%'";
                }
                //拼音码
                if (null != mydyobj.PyCode && !string.IsNullOrWhiteSpace(mydyobj.PyCode.ToString()))
                {
                    strSQL += " and Ptype.PyCode like '%" + mydyobj.PyCode.ToString() + "%'";
                    strsqlcount2 += " and Ptype.PyCode like '%" + mydyobj.PyCode.ToString() + "%'";
                }
                //商品类别 2022-06-14添加商品类别查询条件
                if (null != mydyobj.PtypeCategoryCode && !string.IsNullOrWhiteSpace(mydyobj.PtypeCategoryCode.ToString()))
                {
                    strSQL += " and Ptype.PtypeCategoryID =(select typeid from PtypeCategory where UserCode = '" + mydyobj.PtypeCategoryCode.ToString() + "') ";
                    strsqlcount2 += " and Ptype.PtypeCategoryID =(select typeid from PtypeCategory where UserCode = '" + mydyobj.PtypeCategoryCode.ToString() + "') ";
                }
                if (null == mydyobj.PageIndex2 || string.IsNullOrWhiteSpace(mydyobj.PageIndex2.ToString()))
                {
                    mydyobj.PageIndex2 = 1;
                }
                if (null == mydyobj.PageSize2 || string.IsNullOrWhiteSpace(mydyobj.PageSize2.ToString()))
                {
                    mydyobj.PageSize2 = 2000000000;
                }

                                strSQL += @"order by Ptype.typeid 
                offset " + (mydyobj.PageSize2 * (mydyobj.PageIndex2 - 1)).ToString() + " rows fetch next " + mydyobj.PageSize2.ToString() + @" rows only";

                DataTable dt2 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                result.TotalRows2 = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(strsqlcount2));

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data1 = dt1;
                //   result.TotalRows1 = dt1.Rows.Count;
                result.Data2 = dt2;
                //   result.TotalRows2 = dt2.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data1 = null;
                result.TotalRows1 = 0;
                result.Data2 = null;
                result.TotalRows2 = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 序列号查库存
        /// </summary>
        /// <param name="dyobj"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetSerial(dynamic dyobj)
        {
            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            string strSQL;
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                return Json(result);
            }

            if (null == mydyobj.Serial || string.IsNullOrWhiteSpace(mydyobj.Serial.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Serial不可为空";
                return Json(result);
            }

            if (null == mydyobj.KtypeId || string.IsNullOrWhiteSpace(mydyobj.KtypeId.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "KtypeID不可为空";
                return Json(result);
            }

            try
            {
                //查询仓库ID
                strSQL = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.KtypeId.ToString());
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
                if (dt.Rows.Count <= 0)
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "仓库不存在";
                    return Json(result);
                }

                string Ktypeid = dt.Rows[0]["typeid"].ToString();


                strSQL = "";
                strSQL += "select ";
                strSQL += " gp_CruPtypeSerial.Serial ";//序列号
                strSQL += " ,(select UserCode from stock where typeId = gp_CruPtypeSerial.KtypeID) as KtypeID ";//仓库编号
                strSQL += " ,(select FullName from stock where typeId = gp_CruPtypeSerial.KtypeID) as Kname ";//仓库名称
                strSQL += " ,Ptype.UserCode as PtypeID  "; //商品编号
                strSQL += " ,Ptype.FullName ";//商品名
                strSQL += " ,ISNULL(CostPrice,0) as CostPrice ";//成本单价 2022-06-15添加
                strSQL += " ,ISNULL(gp_CruPtypeSerial.ProduceDate, '') as ProduceDate  ";//生产日期 2022-06-15添加
                strSQL += " ,1 as Qty ";//数量
                strSQL += " ,ISNULL(CostPrice,0) as Price ";//单价			 
                strSQL += " ,1 as Total ";//合计
                strSQL += " ,'' as PrePrice ";//预售价1
                strSQL += " ,ISNULL(b1.UserCode,'') as BTypeID1 ";//客户ID
                strSQL += " ,ISNULL(b2.UserCode,'') as BTypeID2 ";//供货商ID
                strSQL += "  ,gp_CruPtypeSerial.InKtypeTime ";//入库日期
                strSQL += " ,gp_CruPtypeSerial.OutKtypeTime ";//出库日期
                strSQL += " ,gp_CruPtypeSerial.Flag "; //在库标识
                strSQL += " ,ct.UserCode as CargoCode";
                strSQL += " ,ct.FullName as CargoName";
                strSQL += " ,ct.Comment as CargoComment";

                strSQL += " from gp_CruPtypeSerial ";
                strSQL += " left join Ptype on gp_CruPtypeSerial.PtypeID=Ptype.typeId ";
                strSQL += " left join btype as b1 on b1.typeId = gp_CruPtypeSerial.BTypeID1 ";
                strSQL += " left join btype as b2 on b2.typeId = gp_CruPtypeSerial.BTypeID2 ";
                strSQL += " left join CargoType as ct on gp_CruPtypeSerial.CargoID=ct.CargoID";
                strSQL += " where 1=1 ";
                strSQL += " and gp_CruPtypeSerial.Serial =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.Serial.ToString());
                strSQL += " and gp_CruPtypeSerial.KtypeID =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid);



                //序列号列表
                /*
                strSQL += "select ";
                strSQL += " gp_CruPtypeSerial.Serial ";//序列号
                strSQL += " ,GoodsStocks.KtypeID as KtypeID ";//仓库编号
                strSQL += " ,(select FullName from stock where typeId = GoodsStocks.KtypeID) as Kname";//仓库名称
                strSQL += " ,Ptype.UserCode as PtypeID";//商品编号
                strSQL += " ,Ptype.FullName ";//商品名
                strSQL += " ,ISNULL(CostPrice,0) as CostPrice ";//成本单价 2022-06-15添加
                strSQL += " ,ISNULL(gp_CruPtypeSerial.ProduceDate, '') as ProduceDate  ";//生产日期 2022-06-15添加
                strSQL += " ,Convert(int,GoodsStocks.Qty) as Qty ";//数量
                strSQL += " ,ISNULL(GoodsStocks.Price,0) as Price ";//单价
                strSQL += " ,ISNULL(Ptype.preprice1, 0) as PrePrice1 ";//预售价1
                strSQL += " ,GoodsStocks.Total ";//合计

                strSQL += " ,b1.UserCode as BTypeID1 ";//客户ID
                strSQL += " ,b2.UserCode as BTypeID2 ";//供货商ID
                strSQL += " ,gp_CruPtypeSerial.InKtypeTime ";//入库日期
                strSQL += " ,gp_CruPtypeSerial.OutKtypeTime ";//出库日期
                strSQL += " ,gp_CruPtypeSerial.Flag ";//在库标识
                strSQL += " from gp_CruPtypeSerial "; 
                strSQL += " left join Ptype on Ptype.typeId = gp_CruPtypeSerial.PtypeID ";
                strSQL += " left join GoodsStocks on Ptype.typeId = GoodsStocks.PtypeID "; 
                strSQL += " inner join stock on stock.typeId = gp_CruPtypeSerial.KtypeID ";// and stock.typeId = GoodsStocks.KtypeID
                strSQL += " left join btype as b1 on b1.typeId = gp_CruPtypeSerial.BTypeID1 ";
                strSQL += " left join btype as b2 on b2.typeId = gp_CruPtypeSerial.BTypeID2 ";
                strSQL += " where 1=1 ";
                strSQL += " and gp_CruPtypeSerial.Serial =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.Serial.ToString());
                strSQL += " and GoodsStocks.KtypeID =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid);

    */
                string strsqlcount = "";


                strsqlcount = "";
                strsqlcount += "select count(*)";
                strsqlcount += " from gp_CruPtypeSerial ";
                strsqlcount += " left join Ptype on gp_CruPtypeSerial.PtypeID=Ptype.typeId ";
                strsqlcount += " left join btype as b1 on b1.typeId = gp_CruPtypeSerial.BTypeID1 ";
                strsqlcount += " left join btype as b2 on b2.typeId = gp_CruPtypeSerial.BTypeID2 ";
                strsqlcount += " where 1=1 ";
                strsqlcount += " and gp_CruPtypeSerial.Serial =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.Serial.ToString());
                strsqlcount += " and gp_CruPtypeSerial.KtypeID =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid);



                DataTable dt1 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                result.TotalRows = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(strsqlcount));
                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt1;
                // result.TotalRows = dt1.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }
        /// <summary>
        /// 根据序列号模糊查询库存
        /// </summary>
        /// <param name="Serial"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetSerialAndPtypeBySerial([FromBody]SerialPtype model)
        {
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                return Json(result);
            }
            if(string.IsNullOrWhiteSpace(model.Serial))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Serial不可为空";
                return Json(result);
            }
            try
            {
                string strSQL = @"select gp.Serial,gp.KtypeID,Stock.UserCode KCode,Stock.FullName Kname,gp.PtypeID,ptype.UserCode PtypeCode,ptype.FullName PtypeName,
gp.CostPrice,gp.BTypeID1,b1.UserCode BUserCode1,gp.BTypeID2,b2.UserCode BUserCode2,gp.InKtypeTime,gp.OutKtypeTime,gp.Flag,1 as Qty,gp.CostPrice as Price,gp.CostPrice as Total
,ct.UserCode as CargoCode 
,ct.FullName as CargoName 
,ct.Comment as CargoComment
from gp_CruPtypeSerial as gp
left join Stock on Stock.typeId = gp.KtypeID
left join ptype on ptype.typeId = gp.PtypeID
left join btype as b1 on b1.typeId = gp.BTypeID1
left join btype as b2 on b2.typeId = gp.BTypeID2
left join CargoType as ct on gp.CargoID=ct.CargoID
where gp.Serial like '%" + model.Serial + @"%'
order by gp.PkId
offset " + (model.PageSize * (model.PageIndex - 1)).ToString() + " rows fetch next " + model.PageSize.ToString() + @" rows only";

                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;
                result.TotalRows = Convert.ToInt32(FreeADO.DBUtility.DbHelperSQL.GetSingle(connectionString, @"
select count(*) from gp_CruPtypeSerial as gp
left join Stock on Stock.typeId = gp.KtypeID
left join ptype on ptype.typeId = gp.PtypeID
left join btype as b1 on b1.typeId = gp.BTypeID1
left join btype as b2 on b2.typeId = gp.BTypeID2
where gp.Serial like '%" + model.Serial + @"%'"));
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 条码查库存
        /// </summary>
        /// <param name="dyobj"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetPtypeCode(dynamic dyobj)
        {
            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            string strSQL;
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                return Json(result);
            }

            if (null == mydyobj.Code || string.IsNullOrWhiteSpace(mydyobj.Code.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Code不可为空";
                return Json(result);
            }

            if (null == mydyobj.KtypeId || string.IsNullOrWhiteSpace(mydyobj.KtypeId.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "KtypeId不可为空";
                return Json(result);
            }

            try
            {
                //查询仓库ID
                strSQL = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.KtypeId.ToString());
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
                if (dt.Rows.Count <= 0)
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "仓库不存在";
                    return Json(result);
                }

                string Ktypeid = dt.Rows[0]["typeid"].ToString();

                //序列号列表
                strSQL = "";
                strSQL += "select ";
                strSQL += " Ptype.MultEntryCode ";//条码
                strSQL += " ,stock.UserCode as KtypeID ";//仓库编号
                strSQL += " ,stock.FullName as Kname ";//仓库名
                strSQL += " ,Ptype.UserCode as PtypeID";//商品编号
                strSQL += " ,Ptype.FullName as FullName ";//商品名
                strSQL += " ,Convert(int,GoodsStocks.Qty) as Qty ";//数量
                strSQL += " ,GoodsStocks.Price ";//单价
                strSQL += " ,ISNULL(Ptype.preprice1, 0) as PrePrice1 ";//预售价1
                strSQL += " ,GoodsStocks.Total ";//合计
                strSQL += " ,ISNULL(GoodsStocks.ProduceDate, '') as ProduceDate ";//生产日期 2022-06-13
                strSQL += " ,isnull(b1.UserCode,'') as BTypeID ";//供货商ID
                strSQL += " from GoodsStocks ";
                strSQL += " left join Ptype on Ptype.typeId = GoodsStocks.PtypeID ";
                strSQL += " inner join stock on stock.typeId = GoodsStocks.KtypeID ";
                strSQL += " left join btype as b1 on b1.typeId = GoodsStocks.GoodsBTypeID ";

                strSQL += " where 1=1 ";
                strSQL += " and GoodsStocks.KtypeID =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid);
                strSQL += " and Ptype.MultEntryCode like '%" + mydyobj.Code.ToString() + "%'";

                DataTable dt1 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                string strsqlcount = "";
                strsqlcount += "select count(*) ";
                strsqlcount += " from GoodsStocks ";
                strsqlcount += " left join Ptype on Ptype.typeId = GoodsStocks.PtypeID ";
                strsqlcount += " inner join stock on stock.typeId = GoodsStocks.KtypeID ";
                strsqlcount += " left join btype as b1 on b1.typeId = GoodsStocks.GoodsBTypeID ";

                strsqlcount += " where 1=1 ";
                strsqlcount += " and GoodsStocks.KtypeID =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid);
                strsqlcount += " and Ptype.MultEntryCode like '%" + mydyobj.Code.ToString() + "%'";

                result.TotalRows = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(strsqlcount));

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt1;
                //   result.TotalRows = dt1.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }


        /// <summary>
        /// 按分类查询商品
        /// </summary>
        /// <param name="ParId">分类ID</param>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">每页大小</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SearchType(dynamic dyobj)
        {
            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            string strSQL;
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }

            try
            {
                strSQL = "";
                strSQL += "select ";
                strSQL += " Ptype.TypeId ";
                strSQL += " ,Ptype.ParId ";
                strSQL += " ,Ptype.Sonnum ";
                strSQL += " ,Ptype.UserCode ";
                strSQL += " ,Ptype.FullName ";
                strSQL += " ,Ptype.Name ";
                strSQL += " ,Ptype.PyCode ";
                //strSQL += " ,gp_CruPtypeSerial.Serial "; 
                strSQL += " ,Standard ";
                strSQL += " ,Type ";
                strSQL += " ,Unit1 ";
                strSQL += " ,Unit2 ";
                strSQL += " ,Preprice1 ";
                strSQL += " ,Preprice2 ";
                strSQL += " ,Preprice3 ";
                strSQL += " ,Preprice4 ";
                strSQL += " ,Preprice5 ";
                strSQL += " ,Comment ";
                strSQL += " ,EntryCode ";
                strSQL += " ,MultEntryCode ";
                strSQL += " ,IfSerial ";
                strSQL += " ,isnull(Costom1,'') as Costom1 ";
                strSQL += " ,isnull(Costom2,'') as Costom2 ";
                strSQL += " ,isnull(Costom3,'') as Costom3 ";
                strSQL += " ,isnull(Costom4,'') as Costom4 ";
                strSQL += " ,isnull(Costom5,'') as Costom5 ";
                strSQL += " from Ptype ";
                strSQL += " left join Ptype_CustomColumns on Ptype.typeId = Ptype_CustomColumns.typeid ";
                strSQL += " where 1=1 ";
                strSQL += " and Ptype.Parid =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.ParId.ToString());

                strSQL += " order by Ptype.typeId asc ";


                string strsqlcount = "";
                strsqlcount += "select count(*) ";
                strsqlcount += " from Ptype ";
                strsqlcount += " left join Ptype_CustomColumns on Ptype.typeId = Ptype_CustomColumns.typeid ";
                strsqlcount += " where 1=1 ";
                strsqlcount += " and Ptype.Parid =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(mydyobj.ParId.ToString());

                strsqlcount += " order by Ptype.typeId asc ";


                if (!"0".Equals(mydyobj.PageIndex.ToString()) && !"0".Equals(mydyobj.PageSize.ToString()))
                {
                    strSQL += " offset " + (Convert.ToInt32(mydyobj.PageIndex.ToString()) - 1) * Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows fetch next " + Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows only";
                }

                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];




                result.TotalRows = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(strsqlcount));


                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;
                // result.TotalRows = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }
        /// <summary>
        /// 商品可否为赠品设置接口
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdatePtypeIsItGift([FromBody]IsItGiftModel obj)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }

            if (obj == null)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "参数对象不可为空";
                result.Data = "Warning";
            }
            else
            {
                if(string.IsNullOrEmpty(obj.UserCode))
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "UserCode不可为空";
                    result.Data = "Warning";
                }
                else
                {
                    try
                    {
                        string strSql = "update ptype set IsItGift=" + obj.IsItGift + " where UserCode='" + obj.UserCode + "'";
                        int result_num = FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, strSql);

                        if (result_num > 0)
                        {
                            result.Type = AjaxResultType.Success;
                            result.Content = "成功";
                            result.TotalRows = result_num;
                            result.Data = "OK";
                        }
                        else
                        {
                            result.Type = AjaxResultType.Success;
                            result.Content = "执行成功但未修改任何数据，请检查UserCode";
                            result.TotalRows = 0;
                            result.Data = "OK";
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = ex.Message;
                        result.Data = null;
                        result.TotalRows = 0;
                        return Json(result);
                    } 
                }
            }
            return Json(result);
        }


    }
}